package com.ruoyi.project.system.debt.controller;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.project.system.creditor.service.ICreditorService;
import com.ruoyi.project.system.debt.domain.Stage;
import com.ruoyi.project.system.debt.domain.StageView;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.debt.domain.Debt;
import com.ruoyi.project.system.debt.service.IDebtService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 债务管理Controller
 * 
 * @author ruoyi
 * @date 2024-10-06
 */
@Controller
@RequestMapping("/system/debt")
public class DebtController extends BaseController
{
    private String prefix = "system/debt";

    @Autowired
    private IDebtService debtService;

    @Autowired
    private ICreditorService creditorService;

    @RequiresPermissions("system:debt:view")
    @GetMapping()
    public String debt()
    {
        return prefix + "/debt";
    }

    /**
     * 查询债务管理列表
     */
    @RequiresPermissions("system:debt:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Debt debt)
    {
        startPage();
        List<Debt> list = debtService.selectDebtList(debt);
        return getDataTable(list);
    }

    /**
     * 导出债务管理列表
     */
    @RequiresPermissions("system:debt:export")
    @Log(title = "债务管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Debt debt)
    {
        List<Debt> list = debtService.selectDebtList(debt);
        ExcelUtil<Debt> util = new ExcelUtil<Debt>(Debt.class);
        return util.exportExcel(list, "债务管理数据");
    }

    /**
     * 新增债务管理
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        mmap.put("creditors", creditorService.selectCreditorAll());
        return prefix + "/add";
    }

    /**
     * 新增保存债务管理
     */
    @RequiresPermissions("system:debt:add")
    @Log(title = "债务管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Debt debt)
    {
        return toAjax(debtService.insertDebt(debt));
    }

    /**
     * 修改债务管理
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Debt debt = debtService.selectDebtById(id);
        mmap.put("debt", debt);
        return prefix + "/edit";
    }

    /**
     * 分期管理
     */
    @GetMapping("/stage/{id}")
    public String stage(@PathVariable("id") Long id, ModelMap mmap)
    {
        Debt debt = debtService.selectDebtById(id);
        List<StageView> stage = debtService.selectStageById(id);
        mmap.put("debt", debt);
        mmap.put("stages", stage);
        return prefix + "/stage";
    }

    /**
     * 修改保存债务管理
     */
    @RequiresPermissions("system:debt:edit")
    @Log(title = "债务管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Debt debt)
    {
        return toAjax(debtService.updateDebt(debt));
    }

    /**
     * 删除债务管理
     */
    @RequiresPermissions("system:debt:remove")
    @Log(title = "债务管理", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(debtService.deleteDebtByIds(ids));
    }

    /**
     * 新增保存分期管理
     */
    @RequiresPermissions("system:debt:add")
    @Log(title = "分期管理", businessType = BusinessType.INSERT)
    @PostMapping("/addStage")
    @ResponseBody
    public AjaxResult addStage(String data)
    {

        JSONArray jsonArray = JSON.parseArray(data);
        JSONObject jsObj = (JSONObject) JSONObject.parse(String.valueOf(jsonArray.get(0)));
        if(jsObj !=  null){
            debtService.delStage(Long.parseLong(jsObj.get("value").toString()));
        }
        int a = (jsonArray.size()-1)/4;

        String pattern = "\\[(.*?)\\]";
        Pattern r = Pattern.compile(pattern);
        for (int i = 0; i < a; i++) {
            Stage stage = new Stage();
            for (int j = 0; j < jsonArray.size(); j++) {
                JSONObject jsonObject = (JSONObject) JSONObject.parse(String.valueOf(jsonArray.get(j)));
                String aa = String.valueOf(jsonObject.get("name"));
                if("id".equals(aa)){
                    stage.setDebtId(Integer.parseInt(jsonObject.get("value").toString()));
                }
                Matcher m = r.matcher(aa);
                if (m.find()) {
                    if(m.group(1).equals(String.valueOf(i))){
                        if(aa.contains("amt")){
                            stage.setAmt(String.valueOf(jsonObject.get("value")));
                        } else if (aa.contains("num")) {
                            stage.setNum(String.valueOf(jsonObject.get("value")));
                        } else if (aa.contains("repay")) {
                            stage.setRepay(String.valueOf(jsonObject.get("value")));
                        }
                    }
                }
            }
            stage.setCreateBy(ShiroUtils.getLoginName());
            stage.setCreateTime(new Date());
            debtService.insertStage(stage);
        }
        return toAjax(1);
    }
}
